package cn.net.isir.controller.common;

import cn.net.isir.common.CacheManager;
import cn.net.isir.entity.Ticket;
import cn.net.isir.service.TicketService;
import cn.net.isir.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxubo
 * @filename TicketController.java
 * @package cn.net.isir.controller.common
 * @email lxb@isir.net.cn
 * @date 2018/11/16
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/ticket")
public class TicketController {
    private static Logger logger = Logger.getLogger(TicketController.class);

    @Resource
    private TicketService ticketService;

    /**
     * 生成ticket
     *
     * @param request  请求
     * @param response 响应
     * @return 返回结果
     */
    @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
    public Map getNewTicket(HttpServletRequest request, HttpServletResponse response) {
        logger.info(request.getMethod());
        //打印传递过来的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap != null) {
            logger.info("parameters count : " + parameterMap.keySet().size());
            if (parameterMap.keySet().size() > 0) {
                for (String key : parameterMap.keySet()) {
                    String[] values = parameterMap.get(key);
                    logger.info("[" + key + ":");
                    for (String value : values) {
                        logger.info(value);
                    }
                    logger.info("]");
                }
            }
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            logger.info("cookies count : " + cookies.length);
            if (cookies.length > 0) {
                for (Cookie c : cookies) {
                    logger.info("[" + c.getName() + ":" + c.getValue() + "]");
                }
            }
        }

        response.setStatus(200);
//        String ticket = ticketService.GenerTicket();

        String ticket = StringUtils.randomByTime();
        Ticket t = new Ticket();
        t.setTicket(ticket);
        t.setStatus("unused");
        CacheManager.setTicket(ticket, t);

        Logger.getRootLogger().info("=========================web get ticket=========================");
        Logger.getRootLogger().info(ticket);
        Logger.getRootLogger().info("=========================web get ticket=========================");
        Map<String, String> map = new HashMap<>();
        map.put("ticket", ticket);
        return map;
    }
}
